import {
	debounce
} from 'miniprogram-licia'
import {
	reqLogin,
	reqUserInfo
} from '../../api/login'
import {
	setStorage
} from '../../utils/storage'
import {
	ComponentWithStore
} from 'mobx-miniprogram-bindings'
import UserStore from '../../store/index'
ComponentWithStore({
	storeBindings: {
		store: UserStore,
		actions: ['setToken', 'setUserInfo']
	},
	methods: {
		// 登录
		login: debounce(async function () {
			const data = await wx.login()
			if (data.errMsg === "login:ok") {
				const res = await reqLogin(data.code)
				setStorage('token', res.data.token)
				// 存储token到状态仓库
				this.setToken(res.data.token)
				wx.flowerTipToast({
					title: '登录成功',
					icon: "success"
				})
				this.getUserinfo()
			}
		}, 500),
		async getUserinfo() {
			const res = await reqUserInfo()
			if (res.code === 200) {
				setStorage('userInfo', res.data)
				// 存储用户信息到状态仓库
				this.setUserInfo(res.data)
				wx.navigateBack({})
			}
		}
	}
})